package com.sbtr.controller;


import com.sbtr.business.datainfo.service.ConnectInfoService;
import com.sbtr.business.material.service.IMaterialInfoService;
import com.sbtr.business.project.service.IProjectService;
import com.sbtr.common.PageDto;
import com.sbtr.common.Response;
import com.sbtr.constant.ProjectConstant;
import com.sbtr.exception.CustException;
import com.sbtr.impl.MaterialInfoCommon;
import com.sbtr.open.datainfo.dto.SQLRequestDto;
import com.sbtr.open.material.dto.MaterialInfoDto;
import com.sbtr.open.material.dto.MaterialInfoSearchDto;
import com.sbtr.open.project.dto.ProjectDto;
import com.sbtr.open.publishtask.dto.PredictFileDto;
import com.sbtr.util.EasyExcelReader;
import com.sbtr.util.MinioUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;


/**
 * <p>
 * 素材集名称 前端控制器
 * </p>
 *
 * @author wangwh15
 */
@RestController
@RequestMapping("/material-info")
@Api(tags = "素材集接口（用于模型训练各种素材管理，包括文本、数值、图片等等接口，目前主要针对数值预测开发）")
public class MaterialInfoController {


	// 图像类型
    private static final String[] NOR_ARR = {ProjectConstant.PROJECT_TYPE_IMG_DETECTION, ProjectConstant.PROJECT_TYPE_IMG_CLASSIFY, ProjectConstant.PROJECT_TYPE_IMG_SLICING, ProjectConstant.PROJECT_TYPE_IMG_SEGMENT};
    // 声音分类
    private static final String[] SPEC_ARR = {ProjectConstant.PROJECT_TYPE_VOICE_CLASSIFY};
    // 文本分类模式
    private static final String[] TXT_ARR = {ProjectConstant.PROJECT_TYPE_TXT_CLASSIFY};
    // 无监督学习
    private static final String[] DATA_ARR = {ProjectConstant.PROJECT_TYPE_DATA_UNSUPERVISED};
    @Autowired
    private IMaterialInfoService materialInfoService;// 素材中数据的具体信息的
    @Autowired
    private ConnectInfoService connectInfoService;
    @Autowired
    private MaterialInfoCommon materialInfoCommon;// 上传到bucket的
    @Autowired
    private MinioUtil minioUtil;
    // #上传文件路径
    @Value("${oss.config.uploadPath}")
    private String bucketName;
    // 模板文件路径
    @Value("${oss.config.samplePath}")
    private String samplePath;
    private Logger logger = LoggerFactory.getLogger(MaterialInfoController.class);
    //下载文件路径
    @Value("${oss.config.downloadPath}")
    private String downloadPath;
    @Autowired
    private IProjectService projectService;

    @ApiOperation(value = "分页查询", notes = "分页查询", httpMethod = "POST")
    @PostMapping(value = "search")
    public Response<PageDto<MaterialInfoDto>> search(@RequestBody MaterialInfoSearchDto dto, HttpServletRequest request) {
        String algorithmUserId = request.getHeader("algorithmUserId");

        dto.setBelonger(algorithmUserId);
        return Response.success(materialInfoService.search(dto));
    }

    @ApiOperation(value = "单条查询", notes = "单条查询", httpMethod = "POST")
    @PostMapping(value = "findByProjectId")
    public Response<MaterialInfoDto> findByProjectId(@RequestParam(value = "projectId") Long projectId) {

        return Response.success(materialInfoService.findByProjectId(projectId));
    }


//	@ApiOperation(value = "获取数据集类型", notes = "获取数据集类型", httpMethod = "GET")
//	@GetMapping(value = "/get-material-type")
//	public Response<List<String>> getMaterialType(){
//		return Response.success(materialInfoCommon.getMaterialType());
//	}

    @ApiOperation(value = "根据id集合批量删除", notes = "根据id集合批量删除", httpMethod = "DELETE")
    @RequestMapping(value = "batch", method = RequestMethod.DELETE)
    public Response<Boolean> batchDeleteById(@RequestParam("idList") List<Long> idList) {
        boolean b = materialInfoService.batchDeleteById(idList);
        if (b) {
            return Response.success("删除成功", b);
        } else {
            return Response.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "删除失败");
        }
    }

    @ApiOperation(value = "创建素材集", notes = "创建素材集", httpMethod = "POST")
    @PostMapping(value = "/save-no-project")
    public Response<MaterialInfoDto> saveNoProject(@RequestBody MaterialInfoDto dto, HttpServletRequest request) {
        if (dto.getId() == null) {
            String algorithmUserId = request.getHeader("algorithmUserId");
            dto.setBucketDir(bucketName + "/" + dto.getFileType() + "/" + dto.getCreater());
            dto.setCreateTime(new Date());
            dto.setBelonger(algorithmUserId);
        }
        return Response.success("保存成功", materialInfoService.save(dto));
    }

    /**
     * 数据集文件上传接口（无项目时）
     *
     * @param file 上传的文件对象
     * @return 上传成功返回文件url 图片  txt 文件支持通过url 浏览器直接预览
     */

    @ApiOperation(value = "材料文件上传", notes = "材料文件上传", httpMethod = "POST")
    @RequestMapping(value = "/upload-no-project/{id}", method = RequestMethod.POST, headers = "content-type=multipart/form-data")
    public Response<MaterialInfoDto> uploadNoProject(
            @PathVariable("id") Long id,//素材id
            @RequestPart(value = "File") MultipartFile file, HttpServletRequest request) {

        if (file.isEmpty() || file.getSize() == 0) {
            return Response.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "文件不能为空");
        }
        try {
            String algorithmUserId = request.getHeader("algorithmUserId");
            MaterialInfoDto materialInfoDto = materialInfoService.findById(id);
            String fileType = materialInfoDto.getFileType();
            String creater = materialInfoDto.getCreater();
            materialInfoDto.setBelonger(algorithmUserId);
            if (fileType.equals("img_classify")) {
                return Response.success(materialInfoCommon.saveData(materialInfoDto, file, creater, bucketName, "img_classify"));
            } else if (fileType.equals("voice_classify")) {
                return Response.success(materialInfoCommon.saveData(materialInfoDto, file, creater, bucketName, "voice_classify"));
            } else if (fileType.equals("txt_classify")) {
                return Response.success(materialInfoCommon.saveData(materialInfoDto, file, creater, bucketName, "txt_classify"));
            } else if (fileType.equals("data_predict")) {
                return Response.success(materialInfoCommon.saveData(materialInfoDto, file, creater, bucketName, "data_predict"));
            } else if (fileType.equals("data_unsupervised")) {
                return Response.success(materialInfoCommon.saveData(materialInfoDto, file, creater, bucketName, "data_unsupervised"));
            } else if (fileType.equals("img_detection")) {
                return Response.success(materialInfoCommon.saveData(materialInfoDto, file, creater, bucketName, "img_detection"));
            }


//			String url = minioUtil.getObjectUrl("test", newName);
//			return url;
        } catch (Exception e) {
            e.printStackTrace();
            return Response.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "上传失败");
        }
        return Response.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "fileType类型错误，没有对应的项目类型");
    }

    /**
     * 模型管理功能：
     * 新建模型：填写信息-选择数据集（当选择当前已有数据集，点击下一步，进行在线自动关联）
     * @param dto
     * @return
     */
    @ApiOperation(value = "素材和项目关联", notes = "素材和项目关联", httpMethod = "POST")
    @PostMapping(value = "/save")
    public Response<MaterialInfoDto> saveDataMaterial(@RequestBody MaterialInfoDto dto) {
        if (dto.getId() == null || dto.getProjectId() == null) {
            return Response.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "传参错误，素材id或项目id为空");
        }
        ProjectDto projectDto = projectService.findById(dto.getProjectId());
        projectDto.setFileId(dto.getId());
        projectService.update(projectDto);
        return Response.success("保存成功", dto);
    }

//	@ApiOperation(value = "素材和项目关联", notes = "素材和项目关联", httpMethod = "POST")
//	@PostMapping(value = "/save")
//	public Response<MaterialInfoDto> saveDataMaterial(@RequestBody MaterialInfoDto dto) {
//		if (dto.getId() == null || dto.getProjectId() == null) {
//			return Response.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "传参错误，素材id或项目id为空");
//		}
//		return Response.success("保存成功", materialInfoService.savePojectId(dto));
//	}

//	@ApiOperation(value = "创建素材和上传预测文件", notes = "创建素材和上传预测文件", httpMethod = "POST")
//	@RequestMapping(value = "/save-and-upload", method = RequestMethod.POST, headers = "content-type=multipart/form-data")
//	public Response<MaterialInfoDto> saveAndUpload(@RequestParam(value = "fileName") String fileName, @RequestParam(value = "fileDesc") String fileDesc, @RequestParam(value = "projectId") Long projectId, @RequestParam(value = "File") MultipartFile file) {
//		if(materialInfoService.findByProjectId(projectId) != null){
//			return Response.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "正在上传文件中，请不要重复点击");
//		}
//
//		MaterialInfoDto materialInfoDto = new MaterialInfoDto();
//		materialInfoDto.setFileName(fileName);
//		materialInfoDto.setFileDesc(fileDesc);
//		materialInfoDto.setProjectId(projectId);
//		materialInfoDto.setCreateTime(new Date());
////		if (dto.getId() == null) {
//////			dto.setCreater(UserUtils.getFdLoginName());
////			dto.setCreateTime(new Date());
////		}
//		if (file.isEmpty() || file.getSize() == 0) {
//			return Response.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "文件不能为空");
//		}
//		try {
//
////			MaterialInfoDto materialInfoDto = dto;
//			ProjectDto projectDto = projectService.findById(materialInfoDto.getProjectId());
//			String creater=projectDto.getCreater();
//
//			if (StringUtils.endsWithAny(projectDto.getProjectType(), NOR_ARR)) {
//				return Response.success(materialInfoService.saveData(materialInfoDto,file,creater,bucketName,projectDto.getProjectType()));
//			} else if (StringUtils.endsWithAny(projectDto.getProjectType(), SPEC_ARR)) {
//				return Response.success(materialInfoService.saveData(materialInfoDto,file,creater,bucketName,projectDto.getProjectType()));
//			} else if (StringUtils.endsWithAny(projectDto.getProjectType(), TXT_ARR)) {
//				return Response.success(materialInfoService.saveData(materialInfoDto,file,creater,bucketName,projectDto.getProjectType()));
//			}else if(projectDto.getProjectType().equals("data_predict")){
//				return Response.success(materialInfoService.saveData(materialInfoDto,file,creater,bucketName,projectDto.getProjectType()));
//			}else if(projectDto.getProjectType().equals(NOR_ARR[0])){
//				return Response.success(materialInfoService.saveData(materialInfoDto,file,creater,bucketName,projectDto.getProjectType()));
//			}else if(StringUtils.endsWithAny(projectDto.getProjectType(), DATA_ARR)){
//				return Response.success(materialInfoService.saveData(materialInfoDto,file,creater,bucketName,projectDto.getProjectType()));
//			} else {
//				return Response.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "没有对应的项目类型，请检查创建的项目类型");
//			}
//
//		} catch (Exception e) {
//			e.printStackTrace();
//			return Response.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "上传失败");
//		}
//
//	}


    /**
     * 模型管理功能：
     * 新建模型：填写信息-》选择数据集（提交下一步，若是上传文件，则调用该功能进行保存数据集）-》训练模型
     *
     * @param fileName
     * @param fileDesc
     * @param projectId
     * @param file
     * @return
     */
    @ApiOperation(value = "创建素材和上传预测文件", notes = "创建素材和上传预测文件", httpMethod = "POST")
    @RequestMapping(value = "/save-and-upload", method = RequestMethod.POST, headers = "content-type=multipart/form-data")
    public Response<MaterialInfoDto> saveAndUpload(@RequestParam(value = "fileName") String fileName,
                                                   @RequestParam(value = "fileDesc") String fileDesc,
                                                   @RequestParam(value = "projectId") Long projectId,
                                                   @RequestPart(value = "File") MultipartFile file) {
        MaterialInfoDto materialInfoDto = new MaterialInfoDto();
        materialInfoDto.setFileName(fileName);
        materialInfoDto.setFileDesc(fileDesc);
//		materialInfoDto.setProjectId(projectId);
        materialInfoDto.setCreateTime(new Date());
        if (file.isEmpty() || file.getSize() == 0) {
            return Response.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "文件不能为空");
        }
        try {
            ProjectDto projectDto = projectService.findById(projectId);
            String creater = projectDto.getCreater();
            // 图像类型
            if (StringUtils.endsWithAny(projectDto.getProjectType(), NOR_ARR)) {
                return Response.success(materialInfoCommon.saveData2(materialInfoDto, file, creater, bucketName, projectDto.getProjectType(), projectDto));
                // 声音分类
            } else if (StringUtils.endsWithAny(projectDto.getProjectType(), SPEC_ARR)) {
                return Response.success(materialInfoCommon.saveData2(materialInfoDto, file, creater, bucketName, projectDto.getProjectType(), projectDto));
                // 文本类型
            } else if (StringUtils.endsWithAny(projectDto.getProjectType(), TXT_ARR)) {
                return Response.success(materialInfoCommon.saveData2(materialInfoDto, file, creater, bucketName, projectDto.getProjectType(), projectDto));
                // 数据预测
            } else if (projectDto.getProjectType().equals("data_predict")) {
                return Response.success(materialInfoCommon.saveData2(materialInfoDto, file, creater, bucketName, projectDto.getProjectType(), projectDto));
                // 图像检测
            } else if (projectDto.getProjectType().equals(NOR_ARR[0])) {
                return Response.success(materialInfoCommon.saveData2(materialInfoDto, file, creater, bucketName, projectDto.getProjectType(), projectDto));
                // 无监督学习
            } else if (StringUtils.endsWithAny(projectDto.getProjectType(), DATA_ARR)) {
                return Response.success(materialInfoCommon.saveData2(materialInfoDto, file, creater, bucketName, projectDto.getProjectType(), projectDto));
            } else {
                return Response.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "没有对应的项目类型，请检查创建的项目类型");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return Response.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "上传失败");
        }

    }


//	/**
//	 * 文件上传接口
//	 * @param file  上传的文件对象
//	 * @return  上传成功返回文件url 图片  txt 文件支持通过url 浏览器直接预览
//	 */
//
//	@ApiOperation(value = "新增或修改", notes = "新增或修改", httpMethod = "POST")
//	@RequestMapping(value = "/upload/{id}", method = RequestMethod.POST, headers = "content-type=multipart/form-data")
//	public Response<MaterialInfoDto>  upload(
//			@PathVariable("id") Long id,//素材id
//			@RequestParam(value = "File") MultipartFile file) {
//
//		if (file.isEmpty() || file.getSize() == 0) {
//			return Response.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "文件不能为空");
//		}
//		try {
//
//			MaterialInfoDto materialInfoDto = materialInfoService.findById(id);
//			ProjectDto projectDto = projectService.findById(materialInfoDto.getProjectId());
//			String creater=projectDto.getCreater();
//
//			if (StringUtils.endsWithAny(projectDto.getProjectType(), NOR_ARR)) {//图片
//				return Response.success(materialInfoService.saveData(materialInfoDto,file,creater,bucketName,projectDto.getProjectType()));
//			} else if (StringUtils.endsWithAny(projectDto.getProjectType(), SPEC_ARR)) {//声音
//				return Response.success(materialInfoService.saveData(materialInfoDto,file,creater,bucketName,projectDto.getProjectType()));
//			} else if (StringUtils.endsWithAny(projectDto.getProjectType(), TXT_ARR)) {//文本
//				return Response.success(materialInfoService.saveData(materialInfoDto,file,creater,bucketName,projectDto.getProjectType()));
//			}else if(projectDto.getProjectType().equals("data_predict")){//数字
//				return Response.success(materialInfoService.saveData(materialInfoDto,file,creater,bucketName,projectDto.getProjectType()));
//			}
//			else if(projectDto.getProjectType().equals("data_unsupervised")){//无监督
//				return Response.success(materialInfoService.saveData(materialInfoDto,file,creater,bucketName,projectDto.getProjectType()));
//			}
//			else if(projectDto.getProjectType().equals("other")){//无监督
//				return Response.success(materialInfoService.saveData(materialInfoDto,file,creater,bucketName,projectDto.getProjectType()));
//			}
//
//
//
////			String url = minioUtil.getObjectUrl("test", newName);
////			return url;
//		} catch (Exception e) {
//			e.printStackTrace();
//			return Response.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "上传失败");
//		}
//		return null;
//	}


    /**
     * 文件上传接口
     *
     * @param file 上传的文件对象
     * @return 上传成功返回文件url 图片  txt 文件支持通过url 浏览器直接预览
     */

    @ApiOperation(value = "上传预测文件", notes = "上传预测文件", httpMethod = "POST")
    @RequestMapping(value = "/upload", method = RequestMethod.POST, headers = "content-type=multipart/form-data")
    public Response<PredictFileDto> uploadPredictFile(
            @RequestParam(value = "projectId") Long projectId,
            @RequestPart(value = "File") MultipartFile file) {

        if (file.isEmpty() || file.getSize() == 0) {
            return Response.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "文件不能为空");
        }
        try {
            ProjectDto projectDto = projectService.findById(projectId);
            String creater = projectDto.getCreater();

            if (StringUtils.endsWithAny(projectDto.getProjectType(), NOR_ARR)) {
                return Response.success(savePredictData(file, creater, bucketName, projectDto.getProjectType()));
            } else if (StringUtils.endsWithAny(projectDto.getProjectType(), SPEC_ARR)) {
                return Response.success(savePredictData(file, creater, bucketName, projectDto.getProjectType()));
            } else if (StringUtils.endsWithAny(projectDto.getProjectType(), TXT_ARR)) {
                return Response.success(savePredictData(file, creater, bucketName, projectDto.getProjectType()));
            } else if (projectDto.getProjectType().equals("data_predict")) {
                return Response.success(savePredictData(file, creater, bucketName, projectDto.getProjectType()));
            } else if (projectDto.getProjectType().equals("other")) {
                return Response.success(savePredictData(file, creater, bucketName, projectDto.getProjectType()));
            } else if (projectDto.getProjectType().equals("data_unsupervised")) {
                return Response.success(savePredictData(file, creater, bucketName, projectDto.getProjectType()));
            }

        } catch (Exception e) {
            e.printStackTrace();
            return Response.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "上传失败");
        }
        return null;
    }


    // 保存上传的数据信息到数据库
    public PredictFileDto savePredictData(MultipartFile file, String creater,
                                          String bucketName, String fileType) {

        PredictFileDto dto = new PredictFileDto();
        try {
            String fileName = file.getOriginalFilename();
            System.out.println("fileName---------------------------------"+fileName);
            String otherName = UUID.randomUUID().toString().replaceAll("-", "")
                    + fileName.substring(fileName.lastIndexOf("."));
            String newName = fileType + "/" + creater + "/" + otherName;

            dto.setBucketDir(bucketName + "/" + fileType + "/" + creater);
            dto.setFileOSSName(otherName);
            InputStream inputStream = null;
            //桶名 文件路径名 文件 文件类型
//			boolean results = minioUtil.putObject(bucketName, newName, inputStream, file.getContentType());

            OutputStream os = null;
            try {
                inputStream = file.getInputStream();
                // 2、保存到临时文件
                // 1K的数据缓冲
                byte[] bs = new byte[1024];
                // 读取到的数据长度
                int len;
                // 输出的文件流保存到本地文件
                String bucketDir = bucketName + "/" + fileType + "/" + creater;
                File tempFile = new File(bucketDir);
                boolean results = tempFile.mkdirs();
                if (!tempFile.exists()) {
                    tempFile.mkdirs();
                }
                os = new FileOutputStream(tempFile.getPath() + File.separator + otherName);
                // 开始读取
                while ((len = inputStream.read(bs)) != -1) {
                    os.write(bs, 0, len);
                }
                return dto;
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    os.close();
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


//
//	// 保存上传的数据信息到数据库
//	public PredictFileDto savePredictData(MultipartFile file, String creater,
//										  String bucketName, String fileType) {
//
//		PredictFileDto dto=new PredictFileDto();
//		try {
//			String fileName = file.getOriginalFilename();
//			String otherName= UUID.randomUUID().toString().replaceAll("-", "")
//					+ fileName.substring(fileName.lastIndexOf("."));
//			String newName = fileType+"/"+creater+"/" +otherName;
//
//			dto.setBucketDir(bucketName+"/"+fileType+"/"+creater);
//			dto.setFileOSSName(otherName);
//			InputStream inputStream = file.getInputStream();
//			//桶名 文件路径名 文件 文件类型
//			boolean results = minioUtil.putObject(bucketName, newName, inputStream, file.getContentType());
//
//
//			if(results==true){
//				inputStream.close();
//				return dto;
//			}else{
//				inputStream.close();
//				return null;
//			}
//		}catch (Exception e){
//			e.printStackTrace();
//
//		}
//		return null;
//	}


//
//	@ApiOperation(value = "获取文件url", notes = "获取文件url", httpMethod = "POST")
//	@RequestMapping(value = "/getUrl", method = RequestMethod.POST)
//	@ResponseBody
//	public void getUrl(@RequestParam("projectType") String projectType,
//					   HttpServletResponse resp
//	) {
//		OutputStream out;
//		// 读取本地文件的输入流
//		InputStream in;
//		if(projectType.equals("txt_classify")) {
//			try {
//				in = minioUtil.getObject("text", "text.zip");
//				// 设置响应正文的MIME类型
//				resp.setContentType("Content-Disposition;charset=UTF-8");
//				resp.setHeader("Content-Disposition", "attachment;" + " filename=" + "text.zip");
//				// 把本地文件发送给客户端
//				out = resp.getOutputStream();
//				int byteRead = 0;
//				byte[] buffer = new byte[512];
//				while ((byteRead = in.read(buffer)) != -1) {
//					out.write(buffer, 0, byteRead);
//				}
//				in.close();
//				out.flush();
//				out.close();
//			}
//			catch(Exception e)
//			{
//				e.printStackTrace();
//			}
//		}
//
//		else if(projectType.equals("data_predict")){
//			try {
//				in = minioUtil.getObject("data", "data.zip");
//				// 设置响应正文的MIME类型
//				resp.setContentType("Content-Disposition;charset=UTF-8");
//				resp.setHeader("Content-Disposition", "attachment;" + " filename=" + "data.zip");
//				// 把本地文件发送给客户端
//				out = resp.getOutputStream();
//				int byteRead = 0;
//				byte[] buffer = new byte[512];
//				while ((byteRead = in.read(buffer)) != -1) {
//					out.write(buffer, 0, byteRead);
//				}
//				in.close();
//				out.flush();
//				out.close();
//			}
//			catch(Exception e)
//			{
//				e.printStackTrace();
//			}
//
//		}else if(projectType.equals("voice_classify")){
//			try {
//				in = minioUtil.getObject("voice", "voice.zip");
//				// 设置响应正文的MIME类型
//				resp.setContentType("Content-Disposition;charset=UTF-8");
//				resp.setHeader("Content-Disposition", "attachment;" + " filename=" + "voice.zip");
//				// 把本地文件发送给客户端
//				out = resp.getOutputStream();
//				int byteRead = 0;
//				byte[] buffer = new byte[512];
//				while ((byteRead = in.read(buffer)) != -1) {
//					out.write(buffer, 0, byteRead);
//				}
//				in.close();
//				out.flush();
//				out.close();
//			}
//			catch(Exception e)
//			{
//				e.printStackTrace();
//			}
//
//		} else if(projectType.equals("img_detection")){
//			try {
//				in = minioUtil.getObject("image", "image.zip");
//				// 设置响应正文的MIME类型
//				resp.setContentType("Content-Disposition;charset=UTF-8");
//				resp.setHeader("Content-Disposition", "attachment;" + " filename=" + "image.zip");
//				// 把本地文件发送给客户端
//				out = resp.getOutputStream();
//				int byteRead = 0;
//				byte[] buffer = new byte[512];
//				while ((byteRead = in.read(buffer)) != -1) {
//					out.write(buffer, 0, byteRead);
//				}
//				in.close();
//				out.flush();
//				out.close();
//			}
//			catch(Exception e)
//			{
//				e.printStackTrace();
//			}
//		}
//	}


    @ApiOperation(value = "获取文件url", notes = "获取文件url", httpMethod = "POST")
    @RequestMapping(value = "/getUrl", method = RequestMethod.POST)
    @ResponseBody
    public void getUrl(@RequestParam("projectType") String projectType,
                       HttpServletResponse resp
    ) {
        OutputStream out;
        // 读取本地文件的输入流
        InputStream in;
        if (projectType.equals("txt_classify")) {
            try {
                File file = new File(samplePath + File.separator + "text.zip");

                in = new FileInputStream(file);
                // 设置响应正文的MIME类型
//				resp.setContentType("Content-Disposition;charset=UTF-8");
                resp.setHeader("Content-Disposition", "attachment;" + " filename=" + "text.zip");
                // 把本地文件发送给客户端
                out = resp.getOutputStream();
                int byteRead = 0;
                byte[] buffer = new byte[512];
                while ((byteRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, byteRead);
                }
                in.close();
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (projectType.equals("data_predict")) {
            try {
                File file = new File(samplePath + File.separator + "data.zip");
                in = new FileInputStream(file);
                // 设置响应正文的MIME类型
//				resp.setContentType("Content-Disposition;charset=UTF-8");
                resp.setContentType("application/octet-stream");

                resp.setHeader("Content-Disposition", "attachment;" + " filename=" + "data.zip");
                // 把本地文件发送给客户端
                out = resp.getOutputStream();
                int byteRead = 0;
                byte[] buffer = new byte[512];
                while ((byteRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, byteRead);
                }
                in.close();
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else if (projectType.equals("voice_classify")) {
            try {
                File file = new File(samplePath + File.separator + "voice.zip");
                in = new FileInputStream(file);
                // 设置响应正文的MIME类型
//				resp.setContentType("Content-Disposition;charset=UTF-8");
                resp.setContentType("application/octet-stream");

                resp.setHeader("Content-Disposition", "attachment;" + " filename=" + "voice.zip");
                // 把本地文件发送给客户端
                out = resp.getOutputStream();
                int byteRead = 0;
                byte[] buffer = new byte[512];
                while ((byteRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, byteRead);
                }
                in.close();
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else if (projectType.equals("img_classify")) {
            try {
                File file = new File(samplePath + File.separator + "image.zip");
                in = new FileInputStream(file);
                // 设置响应正文的MIME类型
//				resp.setContentType("Content-Disposition;charset=UTF-8");
                resp.setContentType("application/octet-stream");

                resp.setHeader("Content-Disposition", "attachment;" + " filename=" + "image.zip");
                // 把本地文件发送给客户端
                out = resp.getOutputStream();
                int byteRead = 0;
                byte[] buffer = new byte[512];
                while ((byteRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, byteRead);
                }
                in.close();
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (projectType.equals("img_detection")) {
            try {
                File file = new File(samplePath + File.separator + "imgDetection.zip");
                in = new FileInputStream(file);
                // 设置响应正文的MIME类型
//				resp.setContentType("Content-Disposition;charset=UTF-8");
                resp.setContentType("application/octet-stream");

                resp.setHeader("Content-Disposition", "attachment;" + " filename=" + "imgDetection.zip");
                // 把本地文件发送给客户端
                out = resp.getOutputStream();
                int byteRead = 0;
                byte[] buffer = new byte[512];
                while ((byteRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, byteRead);
                }
                in.close();
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (projectType.equals("data_unsupervised")) {
            try {
                File file = new File(samplePath + File.separator + "dataUnsupervised.zip");
                in = new FileInputStream(file);
                // 设置响应正文的MIME类型
//				resp.setContentType("Content-Disposition;charset=UTF-8");
                resp.setContentType("application/octet-stream");

                resp.setHeader("Content-Disposition", "attachment;" + " filename=" + "dataUnsupervised.zip");
                // 把本地文件发送给客户端
                out = resp.getOutputStream();
                int byteRead = 0;
                byte[] buffer = new byte[512];
                while ((byteRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, byteRead);
                }
                in.close();
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @ApiOperation(value = "下载预测文件模板", notes = "下载预测文件模板", httpMethod = "POST")
    @RequestMapping(value = "/downloadPredictTemplate", method = RequestMethod.POST)
    @ResponseBody
    public void downloadModelTemplate(@RequestParam String projectType, HttpServletResponse resp) {

        String filePath = null;
        if (projectType.equals("txt_classify")) {
            filePath = samplePath + "/predict" + "/text.zip";

        } else if (projectType.equals("data_predict")) {
            filePath = samplePath + "/predict" + "/data.zip";

        } else if (projectType.equals("voice_classify")) {
            filePath = samplePath + "/predict" + "/voice.zip";

        } else if (projectType.equals("img_classify")) {
            filePath = samplePath + "/predict" + "/image.zip";

        } else if (projectType.equals("img_detection")) {
            filePath = samplePath + "/predict" + "/imgDetection.zip";

        } else if (projectType.equals("sklearn")) {
            filePath = samplePath + "/predict" + "/sklearn.zip";

        } else if (projectType.equals("matlab")) {
            filePath = samplePath + "/predict" + "/matlab.zip";

        } else {
            throw new IllegalArgumentException("projectType 参数异常:" + projectType);
        }

        OutputStream out;
        // 读取本地文件的输入流
        InputStream in;
        File file = new File(filePath);
        //下载
        try {
            in = new FileInputStream(file);
            // 设置响应正文的MIME类型
            //resp.setContentType( "application/octet-stream");
//			resp.setContentType("Content-Disposition;charset=UTF-8");
            resp.setContentType("application/octet-stream");

            resp.setHeader("Content-Disposition", "attachment;" + " filename=" + file.getName());
            // 把本地文件发送给客户端
            out = resp.getOutputStream();
            int byteRead = 0;
            byte[] buffer = new byte[512];
            while ((byteRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, byteRead);
            }
            in.close();
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 新建模型：模型训练，在线数据预览查询
     * @param response
     * @param fileId
     * @param encoding
     * @return
     */
    @ApiOperation(value = "在线查看文件", notes = "在线查看文件", httpMethod = "GET")
    @RequestMapping(value = "/viewfile", method = RequestMethod.GET)
    public Response<List<String[]>> view(HttpServletResponse response,
                                         @RequestParam("fileId") Long fileId,
                                         @RequestParam("encoding") String encoding) {

        MaterialInfoDto materialInfoDto = materialInfoService.findById(fileId);
        List<String[]> predictData = null;

        if (materialInfoDto.getSqlFile().equals("file")) {
            String combFileName = materialInfoDto.getFileName2();//上传到minio上面的名字
            String dir = materialInfoDto.getBucketDir();
//			String bucketName=dir.substring(0,dir.indexOf("/"));//只显示 data_predict和text类型的
//			dir=dir.substring(dir.indexOf("/")+1,dir.length())+"/"+combFileName;

            if (encoding.equals("") || encoding.isEmpty()) {
                encoding = "UTF-8";
            }
            // 设返回的contentType
            response.setContentType("text/html;charset=utf-8"); // 不同文件的MimeType参考后续链接
            // 读取路径下面的文件
            try {
                File downloadFile = new File(dir.concat(File.separator).concat(combFileName));
                if (!combFileName.toLowerCase().endsWith(".xls") && !combFileName.toLowerCase().endsWith(".xlsx")
                        && !combFileName.toLowerCase().endsWith(".txt") && !combFileName.toLowerCase().endsWith(".csv")) {
                    logger.error(combFileName + " 文件不是excel,csv,txt");
                } else {
                    if (combFileName.toLowerCase().endsWith(".xls") || combFileName.toLowerCase().endsWith(".xlsx")) {
                        try {
                            predictData = new EasyExcelReader().readLessThan1000Row(downloadFile.getAbsolutePath());
                            if (predictData != null && predictData.size() > 10) {
                                predictData = predictData.subList(0, 10);
                            }
                        } catch (Exception e) {
                            logger.error(combFileName + " 读取文件失败", e);
                            throw new CustException(combFileName + " 读取文件失败");
                        }
                    } else {
                        try (InputStreamReader reader = new InputStreamReader(new FileInputStream(downloadFile));
                             BufferedReader br = new BufferedReader(reader);) {
                            predictData = new ArrayList<>();
                            String line = null;
                            int rowFlag = 0;
                            while ((line = br.readLine()) != null) {
                                if (rowFlag == 10) {
                                    break;
                                } else {
                                    rowFlag++;
                                }
                                String[] templine;
                                templine = line.split(",");
                                if (templine.length == 1) {
                                    templine = line.split("[\t]");
                                }
                                predictData.add(templine);
                            }
                        } catch (Exception e) {
                            logger.error(combFileName + " 读取文件失败", e);
                            throw new CustException(combFileName + " 读取文件失败");
                        }
                    }
                }
            } catch (Exception e) {
                logger.error("View cc document exception, document id is [{}]", e);
            }
        } else {
            Long connId = materialInfoDto.getConnId();
            String sqlSyntax = materialInfoDto.getSqlSyntax();
            if (sqlSyntax == null || connId == null) {
                throw new RuntimeException("connId或sqlSyntax不能为空");
            }
            SQLRequestDto requestDto = new SQLRequestDto();
            requestDto.setId(connId);
            requestDto.setSql(sqlSyntax);
            List<Map<String, Object>> lineMapList = connectInfoService.getBySql(requestDto);
            if (null == lineMapList) {
                return Response.error(500, "数据读取失败:数据为空或者只有标题行!");
            }
            predictData = new ArrayList<>();
            String[] templine;
            templine = (String[]) lineMapList.get(0).keySet().toArray(new String[0]);
            predictData.add(templine);
            for (Map<String, Object> lineMap : lineMapList) {
//				templine = (String[])lineMap.values().toArray(new String[0]);
                Object[] templineObject = lineMap.values().toArray();
                templine = new String[templineObject.length];
                for (int i = 0; i < templineObject.length; i++) {
                    templine[i] = templineObject[i].toString();
                }
                predictData.add(templine);
            }
        }

        if (null != predictData && predictData.size() < 2) {
            return Response.error(500, "数据读取失败:数据为空或者只有标题行!", predictData);
        } else {
            return Response.success(predictData);
        }
    }


    @ApiOperation(value = "下载", notes = "下载", httpMethod = "POST")
    @RequestMapping(value = "/download", method = RequestMethod.POST)
    public void downloadFiles(@RequestParam("fileName") String fileName) {

        try {
            File downloadFile = null;
            downloadFile = minioUtil.getObject(bucketName, "data/zengjw5/b48d822e7e834351a5e9ec8f47741c4f.xlsx", "D:\\nlp平台", "test.xlsx");
        } catch (Exception ex) {
            System.out.println("文件下载失败：" + ex.getMessage());
        }
    }

    //待修改
    @ApiOperation(value = "下载数据集", notes = "下载数据集", httpMethod = "POST")
    @RequestMapping(value = "/downloadfile", method = RequestMethod.POST)
    public void downloadfile(HttpServletResponse resp,
                             @RequestParam("fileId") Long fileId) {
        MaterialInfoDto materialInfoDto = materialInfoService.findById(fileId);
        File file = null;
        if (materialInfoDto.getSqlFile().equals("file")) {
            String combFileName = materialInfoDto.getFileName2();//上传到minio上面的名字
            String dir = materialInfoDto.getBucketDir();
            String filePath = dir + "/" + combFileName;
            file = new File(filePath);
        } else {
            List<String[]> predictData = null;
            Long connId = materialInfoDto.getConnId();
            String sqlSyntax = materialInfoDto.getSqlSyntax();
            if (sqlSyntax == null || connId == null) {
                throw new RuntimeException("connId或sqlSyntax不能为空");
            }
            SQLRequestDto requestDto = new SQLRequestDto();
            requestDto.setId(connId);
            requestDto.setSql(sqlSyntax);
            List<Map<String, Object>> lineMapList = connectInfoService.getAllBySql(requestDto);
            if (null == lineMapList) {
                throw new RuntimeException("数据读取失败:数据为空或者只有标题行!");
            }

            String otherName = UUID.randomUUID().toString().replaceAll("-", "")
                    + ".txt";
            String creater = materialInfoDto.getCreater();
            String taskType = materialInfoDto.getFileType();

            file = new File(bucketName + "/" + "download/" + taskType + "/" + creater);
            if (!file.exists()) {
                file.mkdirs();
            }
            file = new File(bucketName + "/" + "download/" + taskType + "/" + creater + "/" + otherName);
            Writer out;
            try {
                out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), "utf-8"), 10240);
                String[] templine;
                templine = (String[]) lineMapList.get(0).keySet().toArray(new String[0]);
                //写入表头
                for (int j = 0; j < templine.length; j++) {
                    if (j == templine.length - 1) {
                        out.write(templine[j] + "\r\n");
                        break;
                    }
                    out.write(templine[j] + "\t");
                }
                //写入数据
                for (Map<String, Object> lineMap : lineMapList) {
                    Object[] templineObject = lineMap.values().toArray();
                    if (templine.length != templineObject.length) {
                        continue;
                    }
                    for (int j = 0; j < templineObject.length; j++) {
                        if (j == templineObject.length - 1) {
                            out.write(templineObject[j] == null ? "NULL" : templineObject[j].toString() + "\r\n");
                            break;
                        }
                        out.write(templineObject[j] == null ? "NULL" : templineObject[j].toString() + "\t");
                    }
                }
                out.flush();
                out.close();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }

        OutputStream out;
        // 读取本地文件的输入流
        InputStream in;

        //下载
        try {
            in = new FileInputStream(file);
            // 设置响应正文的MIME类型
            //resp.setContentType( "application/octet-stream");
//			resp.setContentType("Content-Disposition;charset=UTF-8");
            resp.setContentType("application/octet-stream");

            resp.setHeader("Content-Disposition", "attachment;" + " filename=" + file.getName());
            // 把本地文件发送给客户端
            out = resp.getOutputStream();
            int byteRead = 0;
            byte[] buffer = new byte[512];
            while ((byteRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, byteRead);
            }
            in.close();
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
